var delObj = {},stopObj={};
var setting = {
	data : {
		simpleData : {
			enable : true,
		}
	},
	callback : {
		onClick : showTaskConfig
	}
};
var taskId=0,taskName="test",zTree;
$(function(){
	var url = window.location.href.split("=");
	if(url.length == 2){
		taskId = url[1].replace("#","");
	}
	getTaskTree();
	if(taskId != 0){
		getParamConfig();
	}
	$("#myAudio").initAudio();
})

function getTaskTree(){
	$.ajax({
		type : "post",
		url : "taskTree",
		dataType : "json",
		success : function(data){
			if(data.msg == "success"){
				zTree = $.fn.zTree.init($("#tree"), setting, data.datas);
				zTree.selectNode(zTree.getNodeByParam("id",taskId,null));
			}
		}
	});
}

function showTaskConfig(event, treeId, treeNode){
	if(!treeNode.isParent){
		taskId = treeNode.id;
//		taskName = treeNode.name;
		var activeLi = $("#generalTab > li.active").attr("name");
		if(activeLi == 'param-tab'){
			getParamConfig();
		}else if(activeLi == 'proxy-tab'){
			searchProxy(1);
		}else if(activeLi == 'page-tab'){
			getPageConfig();
		}else if(activeLi == 'fields-tab'){
			searchFields(1);
		}else{
			$("#ths").html('');
			$("#datas").html('');
		}
	}else{
		zTree.expandNode(treeNode);
	}
}

function getParamConfig(){
	$.ajax({
		type : "post",
		data:{"taskId":taskId},
		url : "getParamConfigByTaskId",
		dataType : "json",
		success : function(data){
			if(data.msg == "success"){
				var config = data.data;
				if(config != null && config != 'null'){
					$("#configId").val(config.id);
					$("#threadCount").val(config.threadCount);
					$("#threadSleepTime").val(config.sleepTime);
					$("#connectTimeOut").val(config.connectTimeOut);
					$("#retryCount").val(config.reConnectCount);
					$("#retryInterval").val(config.reConnectTimeIinterval);
					$("#charset").val(config.charset);
					$("#domain").val(config.domain);
					$("#cookies").val(config.cookies);
					$("#headers").val(config.headers);
				}else{
					$("#configId").val("");
					$("#threadCount").val("1");
					$("#threadSleepTime").val("1");
					$("#connectTimeOut").val("30");
					$("#retryCount").val("2");
					$("#retryInterval").val("30");
					$("#charset").val("");
					$("#domain").val("");
					$("#cookies").val("");
					$("#headers").val("");
				}
			}
		}
	});
}

function getPageConfig(){
	$.ajax({
		type : "post",
		data:{"taskId":taskId},
		url : "getPageConfigByTaskId",
		dataType : "json",
		success : function(data){
			if(data.msg == "success"){
				var config = data.data;
				if(config != null && config != 'null'){
					$("#pageConfigId").val(config.id);
					$("#initUrl").val(config.initUrl);
					$("#listUrlRegex").val(config.listUtlRegex);
					$("#detailUrlRegex").val(config.detailUrlRegex);
					$("#isListUrlFromJson").val(config.isListUrlFromJson);
					$("#isDetailUrlFromJson").val(config.isDetailUrlFromJson);
					$("#pageRuleType").val(config.pageRuleType);
					$("#detailRuleType").val(config.detailRuleType);
					$("#pageRule").val(config.pageKey);
					$("#detailRule").val(config.detailRule);
					showRegexInput(document.getElementById("isListUrlFromJson"),"pageRuleDiv");
					showRegexInput(document.getElementById("isDetailUrlFromJson"),"detailRuleDiv");
				}else{
					$("#pageConfigId").val("");
					$("#initUrl").val("");
					$("#listUrlRegex").val("");
					$("#detailUrlRegex").val("");
					$("#isListUrlFromJson").val("0");
					$("#isDetailUrlFromJson").val("0");
					$("#pageRuleType").val("0");
					$("#detailRuleType").val("0");
					showRegexInput(document.getElementById("isListUrlFromJson"),"pageRuleDiv");
					showRegexInput(document.getElementById("isDetailUrlFromJson"),"detailRuleDiv");
					$("#pageRule").val("");
					$("#detailRule").val("");
				}
			}
		}
	});
}

function saveOrUpdatePageConfig(){
	var params = {};
	var id = $("#pageConfigId").val();
	if(id != ''){
		params["id"] = id;
	}
	var initUrl = $.trim($("#initUrl").val());
	var listUtlRegex = $.trim($("#listUrlRegex").val());
	var detailUrlRegex = $.trim($("#detailUrlRegex").val());
	if(checkEmpty(initUrl,"请输入入口页面") || checkEmpty(listUtlRegex,"请输入列表页正则表达式") 
			|| checkEmpty(detailUrlRegex,"请输入详情页正则表达式")){
		return;
	}
	var isListUrlFromJson = $("#isListUrlFromJson").val();
	var pageRule = $.trim($("#pageRule").val());
	if(isListUrlFromJson == '1' && checkEmpty(pageRule,"请输入列表页地址动态生成规则")){
		return;
	}
	var isDetailUrlFromJson = $("#isDetailUrlFromJson").val();
	var detailRule = $.trim($("#detailRule").val());
	if(isDetailUrlFromJson == '1' && checkEmpty(detailRule,"请输入详情页地址动态生成规则")){
		return;
	}
	params["initUrl"] = initUrl;
	params["listUtlRegex"] = listUtlRegex;
	params["detailUrlRegex"] = detailUrlRegex;
	params["isListUrlFromJson"] = isListUrlFromJson;
	params["isDetailUrlFromJson"] = isDetailUrlFromJson;
	params["pageRuleType"] = $("#pageRuleType").val();
	params["detailRuleType"] = $("#detailRuleType").val();
	params["pageKey"] = pageRule;
	params["detailRule"] = detailRule;
	params["taskId"] = taskId;
	$.ajax({
		type : "post",
		data:params,
		url : "saveOrUpdatePageConfig",
		dataType : "json",
		success : function(data){
			if(data.msg){
				layer.msg("保存成功");
				$("#pageConfigId").val(data.id);
			}else{
				layer.msg("保存失败");
			}
		}
	});
}

function saveOrUpdateConfig(){
	var params = {};
	var id = $("#configId").val();
	if(id != ''){
		params["id"] = id;
	}
	var threadCount = $.trim($("#threadCount").val());
	var sleepTime = $.trim($("#threadSleepTime").val());
	var connectTimeOut = $.trim($("#connectTimeOut").val());
	var reConnectCount = $.trim($("#retryCount").val());
	var reConnectTimeIinterval = $.trim($("#retryInterval").val());
	if(checkEmpty(threadCount,"请输入线程数") || !isPositiveNum(threadCount,"线程数必须为大于0的整数")
			|| checkEmpty(sleepTime,"请输入线程睡眠时间") || !isNum(sleepTime,"线程睡眠时间必须为整数")
			|| checkEmpty(connectTimeOut,"请输入连接超时时间") || !isPositiveNum(connectTimeOut,"连接超时时间必须为大于0的整数")
			|| checkEmpty(reConnectCount,"请输入重试次数") || !isNum(reConnectCount,"重试次数必须为整数")
			|| checkEmpty(reConnectTimeIinterval,"请输入重试间隔") || !isPositiveNum(reConnectTimeIinterval,"重试间隔必须为大于0的整数")){
		return;
	}
	params["threadCount"] = threadCount;
	params["sleepTime"] = sleepTime;
	params["connectTimeOut"] = connectTimeOut;
	params["reConnectCount"] = reConnectCount;
	params["reConnectTimeIinterval"] = reConnectTimeIinterval;
	params["charset"] = $.trim($("#charset").val());
	var domain = $.trim($("#domain").val());
	var cookies = $.trim($("#cookies").val());
	if(!checkEmpty(cookies) && checkEmpty(domain,"请输入域名")){
		return;
	}
	params["domain"] = domain;
	params["cookies"] = cookies;
	params["headers"] = $.trim($("#headers").val());
	params["taskId"] = taskId;
	$.ajax({
		type : "post",
		data:params,
		url : "saveOrUpdateGatherConfig",
		dataType : "json",
		success : function(data){
			if(data.msg){
				layer.msg("保存成功");
				$("#configId").val(data.id);
			}else{
				layer.msg("保存失败");
			}
		}
	});
}
function searchProxy(){
	searchObj["method"] = "searchProxy";
	delObj = {tip:'确认删除所选代理吗?',url:"deleteTaskProxy"};
	stopObj = {stopTip:'确认停用所选代理吗?',startTip:'确认启用所选代理吗?',url:"updateProxyStatus"};
	checkboxName = 'checkProxy';
	var currPage = arguments[0];
	$.ajax({
		type : "post",
		url : "taskProxyPageListByTaskId",
		data : {
			"taskId":taskId,
			"status":$("#proxyStatus").val(),
			"start":currPage
		},
		dataType : "json",
		success : function(data) {
			if(data.msg == 'success'){
				var html = '';
				$.each(data.datas,function(k,v){
					html += '<tr><td><input type="checkbox" name="checkProxy" value='+v.id+' /></td>'
								+'<td>'+(k+1)+'</td>'
								+'<td><label>'+v.ip+'</label></td>'
								+'<td><label>'+v.port+'</label></td>'
								+'<td><label>'+(checkEmpty(v.userName)?"":v.userName)+'</label></td>'
								+'<td><label>'+(checkEmpty(v.password)?"":v.password)+'</label></td>'
								+'<td><label class="label label-sm label-'+(v.status==-1?"danger":"success")+'">'+(v.status==-1?"已停用":"已启用")+'</label></td>'
								+'<td ip="'+v.ip+'" port="'+v.port+'" id="'+v.id+'" userName="'+v.userName+'" password="'+v.password+'">'
								+'<button type="button" class="btn btn-yellow btn-xs" onclick="addOrEditProxy(this);">编辑</button>&nbsp;&nbsp;&nbsp;'	
								+'<button type="button" class="btn btn-yellow btn-xs" onclick="stopOne(\''+v.id+'\','+(v.status==-1?1:-1)+');">'+(v.status==-1?"启用":"停用")+'</button>&nbsp;&nbsp;&nbsp;'	
								+'<button type="button" class="btn btn-red btn-xs" onclick="delOne(\''+v.id+'\');">删除</button>&nbsp;&nbsp;&nbsp;'
								+'</td></tr>';
				});
				$("#proxys").html(html);
				laypage({
					cont : document.getElementById('pageProxy'), //容器。值支持id名、原生dom对象，jquery对象,
					pages : data.pages, //总页数
					skip : true, //是否开启跳页
					skin : 'molv', //加载内置皮肤，也可以直接赋值16进制颜色值，如:#c00
					curr : currPage,
					last: data.pages,
					groups : 6,//连续显示分页数
					jump : function(obj, first) { //触发分页后的回调
						if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
							searchProxy(obj.curr);
						}
					}
				});
			}else{
				layer.msg("获取数据失败");
			}
			
		},
		error : function(data) {
			layer.msg("获取数据失败");
		}
	});
}

function searchFields(){
	searchObj["method"] = "searchFields";
	delObj = {tip:'确认删除所选采集字段吗?',url:"deleteTaskField"};
	stopObj = {stopTip:'确认停用所选采集字段吗?',startTip:'确认启用所选采集字段吗?',url:"updateFieldStatus"};
	checkboxName = 'checkField';
	var currPage = arguments[0];
	$.ajax({
		type : "post",
		url : "taskFieldPageListByTaskId",
		data : {
			"taskId":taskId,
			"status":$("#fieldStatus").val(),
			"start":currPage
		},
		dataType : "json",
		success : function(data) {
			if(data.msg == 'success'){
				var html = '';
				$.each(data.datas,function(k,v){
					html += '<tr><td><input type="checkbox" name="checkField" value='+v.id+' /></td>'
								+'<td>'+(k+1)+'</td>'
								+'<td><label>'+v.cnName+'</label></td>'
								+'<td><label>'+v.enName+'</label></td>'
								+'<td><label>'+v.rule+'</label></td>';
					if(v.ruleType == 1){
						html += '<td><label>常量</label></td>';
					}else if(v.ruleType == 2){
						html += '<td><label>xpath</label></td>';
					}else if(v.ruleType == 3){
						html += '<td><label>正则</label></td>';
					}else{
						html += '<td><label>元素选择器</label></td>';
					}
					if(v.valueType == 1){
						html += '<td><label>纯文本</label></td>';
					}else if(v.valueType == 2){
						html += '<td><label>内部html</label></td>';
					}else if(v.valueType == 3){
						html += '<td><label>外部html</label></td>';
					}else{
						html += '<td><label>地址参数</label></td>';
					}
					html +=	'<td><label>'+(v.imgType ==1 ?"是":"否")+'</label></td>'
							+'<td><label>'+(v.videoType==1?"是":"否")+'</label></td>'
							+'<td><label>'+(v.audioType==1?"是":"否")+'</label></td>'
							+'<td><label>'+(v.fileType==1?"是":"否")+'</label></td>'
							+'<td><label class="label label-sm label-'+(v.status==-1?"danger":"success")+'">'+(v.status==-1?"已停用":"已启用")+'</label></td>'
							+'<td cnName="'+v.cnName+'" enName="'+v.enName+'" rule="'+v.rule+'" ruleType="'+v.ruleType+'" id="'+v.id+'" valueType="'+v.valueType+'" imgType="'+v.imgType+'" videoType="'+v.videoType+'" audioType="'+v.audioType+'" fileType="'+v.fileType+'">'
							+'<button style="float:left;margin-right:5px;margin-bottom:5px;" type="button" class="btn btn-yellow btn-xs" onclick="addOrEditField(this);">编辑</button>'	
							+'<button style="float:left;margin-right:5px;margin-bottom:5px;" type="button" class="btn btn-yellow btn-xs" onclick="stopOne(\''+v.id+'\','+(v.status==-1?1:-1)+');">'+(v.status==-1?"启用":"停用")+'</button>'	
							+'<button type="button" class="btn btn-red btn-xs" onclick="delOne(\''+v.id+'\');">删除</button>'
							+'</td></tr>';
				});
				$("#fields").html(html);
				laypage({
					cont : document.getElementById('pageFields'), //容器。值支持id名、原生dom对象，jquery对象,
					pages : data.pages, //总页数
					skip : true, //是否开启跳页
					skin : 'molv', //加载内置皮肤，也可以直接赋值16进制颜色值，如:#c00
					curr : currPage,
					last: data.pages,
					groups : 6,//连续显示分页数
					jump : function(obj, first) { //触发分页后的回调
						if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
							searchFields(obj.curr);
						}
					}
				});
			}else{
				layer.msg("获取数据失败");
			}
			
		},
		error : function(data) {
			layer.msg("获取数据失败");
		}
	});
}

function addOrEditProxy(){
	$("#proxyId").val("");
	$("#addProxyIp").val("");
	$("#addProxyPort").val("");
	$("#addProxyUserName").val("");
	$("#addProxyPassword").val("");
	var o,title="新增采集代理";
	if(arguments.length != 0){
		o = arguments[0];
		title="编辑采集代理"
	}
	layer.open({
		title:title,
		type: 1,
		area : [ '600px', '510px' ],
		content: $('#addProxy'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
		btn: ['保存', '关闭'],
		yes: function(index){
			var proxyIp = $.trim($("#addProxyIp").val());
			var proxyPort = $("#addProxyPort").val();
			if(checkEmpty(proxyIp,"请输入ip") || !isIp(proxyIp,"请输入有效的ip")
				|| checkEmpty(proxyPort,"请输入端口号") || !isNum(proxyPort,"请输入有效的端口号")){
				return;
			}
			var userName = $.trim($("#addProxyUserName").val());
			var password = $.trim($("#addProxyPassword").val());
			if((checkEmpty(userName) && !checkEmpty(password))
					|| (!checkEmpty(userName) && checkEmpty(password))){
				layer.msg("用户名和密码必须同时输入");
				return;
			}
			var proxy = {};
			var id = $("#proxyId").val();
			if(id != ""){
				proxy["id"] = id;
			}
			proxy["ip"] = proxyIp;
			proxy["port"] = proxyPort;
			proxy["userName"] = userName;
			proxy["password"] = password;
			proxy["taskId"] = taskId;
			$.post("saveOrUpdateGatherProxy",proxy, function(data) {
				if(!data.msg){
					layer.msg("保存失败");
				}else{
					layer.msg("保存成功");
					layer.close(index);
					searchProxy(1);
				}
			});
		},
		close: function(){
			
		},
		success:function(){
			if(o){
				var parent = $(o).parent(); 
				$("#proxyId").val(parent.attr("id"));
				$("#addProxyIp").val(parent.attr("ip"));
				$("#addProxyPort").val(parent.attr("port"));
				$("#addProxyUserName").val(checkEmpty(parent.attr("userName"))?'':parent.attr("userName"));
				$("#addProxyPassword").val(checkEmpty(parent.attr("password"))?'':parent.attr("password"));
			}
		}
	});
}

function addOrEditField(){
	$("#fieldId").val("");
	$("#cnName").val("");
	$("#enName").val("");
	$("#rule").val("");
	$("#ruleType").val("1");
	$("#valueType").val("1");
	$("#imgType").val("0");
	$("#videoType").val("0");
	$("#audioType").val("0");
	$("#fileType").val("0");
	var o;
	if(arguments.length != 0){
		o = arguments[0];
	}
	layer.open({
		title:"新增采集字段",
		type: 1,
		area : [ '600px', '710px' ],
		content: $('#addField'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
		btn: ['保存', '关闭'],
		yes: function(index){
//			var proxyIp = $.trim($("#addProxyIp").val());
//			if(proxyIp == ''){
//				layer.msg('请输入代理ip');
//				return;
//			}
//			var proxyPort = $("#addProxyPort").val();
//			if(proxyPort == ''){
//				layer.msg('请输入代理端口号');
//				return;
//			}
			var field = {};
			var id = $("#fieldId").val();
			if(id != ""){
				field["id"] = id;
			}
			var cnName = $.trim($("#cnName").val());
			var enName = $.trim($("#enName").val());
			var ruleType = $.trim($("#ruleType").val());
			var rule = $.trim($("#rule").val());
			var valueType = $.trim($("#valueType").val());
			var imgType = $.trim($("#imgType").val());
			var videoType = $.trim($("#videoType").val());
			var audioType = $.trim($("#audioType").val());
			var fileType = $.trim($("#fileType").val());
			field["cnName"] = cnName;
			field["enName"] = enName;
			field["ruleType"] = ruleType;
			field["rule"] = rule;
			field["valueType"] = valueType;
			field["imgType"] = imgType;
			field["videoType"] = videoType;
			field["audioType"] = audioType;
			field["fileType"] = fileType;
			field["taskId"] = taskId;
			$.post("saveOrUpdateGatherField",field, function(data) {
				if(!data.msg){
					layer.msg("保存失败");
				}else{
					layer.msg("保存成功");
					layer.close(index);
					searchFields(1);
				}
			});
		},
		close: function(){
			
		},
		success:function(){
			if(o){
				var parent = $(o).parent(); 
				var cnName = $.trim($("#cnName").val());
				var enName = $.trim($("#enName").val());
				var ruleType = $.trim($("#ruleType").val());
				var rule = $.trim($("#rule").val());
				var valueType = $.trim($("#valueType").val());
				var imgType = $.trim($("#imgType").val());
				var videoType = $.trim($("#videoType").val());
				var fileType = $.trim($("#fileType").val());
				$("#fieldId").val(parent.attr("id"));
				$("#cnName").val(parent.attr("cnName"));
				$("#enName").val(parent.attr("enName"));
				$("#ruleType").val(parent.attr("ruleType"));
				$("#rule").val(parent.attr("rule"));
				$("#valueType").val(parent.attr("valueType"));
				$("#imgType").val(parent.attr("imgType"));
				$("#videoType").val(parent.attr("videoType"));
				$("#audioType").val(parent.attr("audioType"));
				$("#fileType").val(parent.attr("fileType"));
			}
		}
	});
}

function showRegexInput(obj,divId){
	if($(obj).val() == "0"){
		$("#"+divId).hide();
	}else{
		$("#"+divId).show();
	}
}

function testGather(){
	layer.msg("开始抓取");
	$.ajax({
		type : "post",
		url : "run",
		data : {
			"taskId":taskId,
			"isTestRun":true
		},
		dataType : "text",
		success : function(data) {
			//window.setInterval("listTestData()",2000);
		}
	});
}

function listTestData(){
	$.ajax({
		type : "post",
		url : "listTestData",
		data : {
			"taskId":taskId
		},
		dataType : "json",
		success : function(data) {
			if(data.msg == 'success'){
				var dataHtml = '';
				var thHtml = '<tr><th>序号</th>';
				var ths = [];
				$.each(data.datas,function(k,v){
					if(k == 0){
						$.each(v,function(th,value){
							if(th !='_id' && th != '_class'){
								if(th != 'originalUrl'){
									thHtml += '<th>'+th+'</th>';
								}else{
									thHtml += '<th>操作</th>';
								}
								ths.push(th);
							}
							
						});
						thHtml += '</tr>';
						$("#ths").html(thHtml);
					}
					dataHtml += '<tr><td>'+(k+1)+'</td>';
					for(var i=0;i<ths.length;i++){
						if(ths[i] != 'originalUrl'){
							dataHtml += '<td title="'+v[ths[i]]+'"><label>'+v[ths[i]].substring(0,50)+'</label></td>';
						}else{
							dataHtml += '<td>'
								+'<a style="float:left;margin-bottom:5px;margin-right:5px;" target="blank" type="button" class="btn btn-success btn-xs" href="'+v[ths[i]]+'">查看原网页</a>'
								+'<button onclick="listImgs(\''+v["_id"]+'\')" style="float:left;margin-right:5px;margin-bottom:5px;" type="button" class="btn btn-success btn-xs">查看图片</button>'
								+'<button onclick="listVideos(\''+v["_id"]+'\')" style="float:left;margin-right:5px;margin-bottom:5px;" type="button" class="btn btn-success btn-xs">查看视频</button>'
								+'<button onclick="listAudios(\''+v["_id"]+'\')" style="float:left;margin-right:5px;margin-bottom:5px;" type="button" class="btn btn-success btn-xs">查看音频</button>'
								+'<button onclick="listFiles(\''+v["_id"]+'\')" style="float:left;" type="button" class="btn btn-success btn-xs">查看附件</button>'
								+'</td>';
						}
					}
					dataHtml+= '</tr>';
				});
				if(dataHtml == ''){
					layer.msg("暂无抓取到数据,请稍后再试");
				}else{
					$("#datas").html(dataHtml);
				}
			}else{
				layer.msg("获取数据失败");
			}
		}
	});
}